'use strict';
// 按钮数据
const Controller = require('egg').Controller;

class NavController extends Controller {
    async edit() {
        const { ctx, app } = this
        const { id, nav_id, name, url } = ctx.request.body
        ctx.validate({
            nav_id: {
                type: 'int',
                required: true,
                desc: '导航栏id'
            },
            name: {
                type: 'string',
                required: true,
                desc: '名称'
            },
            url: {
                type: 'string',
                required: true,
                desc: '关键词'
            },

        })
        let oneList, twoList
        if (! await app.model.AdminNav.findByPk(nav_id)) {
            ctx.throw(400, '导航栏数据不存在')
        }
        if (id == 0) {//新建
            twoList = await app.model.AdminBtn.create({
                nav_id, name, url
            })
        } else {//编辑
            oneList = await app.model.AdminBtn.findByPk(id)
            if (!oneList) {
                ctx.throw(400, '数据不存在')
            }
            twoList = await oneList.update({ nav_id, name, url })
        }
        ctx.apiSuccess(twoList)
    }
    async list() {
        const { ctx, app } = this
        let { name, nav_id } = ctx.query
        let where = {}
        let Op = app.Sequelize.Op;
        if (name != "" && name != undefined) {
            where.name = {
                [Op.like]: '%' + name + '%'
            }
        }
        if (nav_id != "" && nav_id != undefined) {
            where.nav_id = nav_id
        }
        let oneList = await ctx.page(app.model.AdminBtn, where)
        ctx.apiSuccess(oneList)
    }
    async del() {
        const { ctx, app } = this
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: 'id'
            }
        })
        let id = ctx.query.id
        let oneList = await app.model.AdminBtn.findByPk(id)
        if (!oneList) {
            ctx.throw(400, '数据不存在')
        }
        oneList = await oneList.destroy()
        if (!oneList) {
            ctx.throw(400, '操作失败')
        }
        ctx.apiSuccess('删除成功')
    }
}

module.exports = NavController;
